import java.util.HashMap;

public class Solution778_2 {
    int[] R=new int[]{1,0,-1,0};
    int[] C=new int[]{0,1,0,-1};
    int m;
    int n;
    private class UnionUtil{
        HashMap<Integer,Integer> Util;
        int Count;
        UnionUtil(){
            Util=new HashMap<>();
            Count=0;
        }
        int getCount(){
            return Count;
        }
        int find(int element){
            if(Util.containsKey(element)==false){
                Util.put(element,element);
                Count++;
            }
            if(Util.get(element)!=element){
                Util.put(element,find(Util.get(element)));
            }
            return Util.get(element);
        }
        boolean union(int x,int y){
            int rootx=find(x);
            int rooty=find(y);
            if(rootx==rooty){
                return false;
            }
            Util.put(rootx,rooty);
            Count--;
            return true;
        }
    }

    public boolean check(UnionUtil util){
        if(util.Util.containsKey(0)==false){
            return false;
        }
        if(util.Util.containsKey((10*(m-1))+n-1)==false){
            return false;
        }
        return util.find(0)== util.find((10*(m-1))+n-1);
    }

    public int swimInWater(int[][] grid) {
        m=grid.length;
        n=grid[0].length;
        UnionUtil util=new UnionUtil();
        int time=0;
        while(!check(util)){
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if(grid[i][j]!=time){
                        continue;
                    }
                    util.find((i*10)+j);
                    for (int k = 0; k < R.length; k++) {
                        int newM=i+R[k];
                        int newN=j+C[k];
                        if(0<=newM&&newM< grid.length&&0<=newN&&newN< grid[0].length){
                            if(util.Util.containsKey((newM*10)+newN)){
                                util.union((i*10)+j,(newM*10)+newN);
                            }
                        }
                    }
                }
            }
            time++;
        }
        return time-1;
    }
    public static void main(String[] args) {
        Solution778_2 s=new Solution778_2();
        System.out.println(s.swimInWater(new int[][]{{0,2},{1,3}}));
    }
}
